/**
 * Author: Kai Jiang
 * Date: Apr 12, 2014
 * Course: CS201 
 * Homework #1 Typing speed game
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>

int main(int argc, char **argv){
	//counter
	int i;
	int random;
	//length of word
	int len;
	int flag;

	//words
	char word[][10]={"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
	char tmp[10];

	struct timeval timer;
	struct timeval cnt,a,b;

	gettimeofday(&timer,NULL);
	
	//initalize the seed
	srand((timer.tv_sec * 1000) + (timer.tv_usec / 1000));
	
	//random array of words
	for ( i = 8; i >= 2; --i){
		random = rand() % ( i - 1 );
		strcpy( tmp, word[i] );
		strcpy( word[i], word[random]);
		strcpy( word[random], tmp);
	}

	printf("This is a game that tests typing speed\n\nType the following words:\n");
	//test typing speed
	timerclear(&cnt);

	for ( i = 0; i < 9; ++i){
		flag = 1;
		do{
			if ( flag == 0){
				printf("Incorrect.  Try again.\n");
			}
			else
				flag = 0;
			printf("  word #%d is %s: ", i + 1, word[i]);
			gettimeofday(&a,NULL);
			scanf("%s", tmp);
			gettimeofday(&b,NULL);
			timersub(&b,&a,&a);
		}while( strncmp( tmp, word[i], strlen(tmp)) ||  !(strlen(tmp) == strlen(word[i]))  );
		// printf("%d.%d\n", (int)a.tv_sec,(int)a.tv_usec);
		timeradd(&a,&cnt,&cnt);
	}

	//result
	printf("\nCorrect!  Your time is: %d sec  %d usec\n",(int)cnt.tv_sec,(int)cnt.tv_usec);

	return 0;
}